import React, { useState, useEffect } from 'react';
import { Container, ListGroup, Form, Button, Image } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';

const apiUrl = process.env.REACT_APP_NEWS_URL;
const deleteUrl = process.env.REACT_APP_DELETE_URL;

const Delete = () => {
  const [newsList, setNewsList] = useState([]);
  const [selectedNews, setSelectedNews] = useState([]);
  const navigate = useNavigate();

  useEffect(() => {
    fetchNews();
  }, []);

  const fetchNews = async () => {
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ method: 'get_news_list' }),
    });
    const data = await response.json();
    if (response.ok) {
      setNewsList(data);
    } else {
      alert('获取新闻列表失败: ' + data.error);
    }
  };

  const handleNewsChange = (event, newsId) => {
    const newSelectedNews = [...selectedNews];
    const index = newSelectedNews.indexOf(newsId);
    if (event.target.checked) {
      if (index === -1) newSelectedNews.push(newsId);
    } else if (index !== -1) {
      newSelectedNews.splice(index, 1);
    }
    setSelectedNews(newSelectedNews);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    const token = localStorage.getItem('token');
    if (!token) {
      alert('未登录或登录已过期');
      return;
    }

    const response = await fetch(deleteUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
      },
      body: JSON.stringify({ ids: selectedNews }),
    });
    const data = await response.json();
    if (response.ok) {
      alert('新闻删除成功');
      fetchNews(); // 重新获取新闻列表
    } else {
      alert('删除失败: ' + data.error);
    }
  };

  return (
    <Container className="mt-5">
      <h1>删除新闻</h1>
      <Form onSubmit={handleSubmit}>
        <ListGroup>
          {newsList.map((news) => (
            <ListGroup.Item key={news.id}>
              <Form.Check
                type="checkbox"
                label={news.title}
                onChange={(e) => handleNewsChange(e, news.id)}
                checked={selectedNews.includes(news.id)}
              />
              <p>{news.summary}</p>
            </ListGroup.Item>
          ))}
        </ListGroup>
        <Button variant="primary" type="submit">
          删除选中
        </Button>
      </Form>
    </Container>
  );
};

export default Delete;